import os
import re
import sys

def printf(fmt,*args):
    sys.stdout.write(fmt % args)
    sys.stdout.flush()

#source=['derc_01.c', 'derc_02.c', 'derc_03.c', 'gabc.c', 'gagc.c', 'hsbc.c', 'hsgc.c', 'hsrc.c']
#source=['derc_01.c', 'derc_02.c', 'derc_03.c', 'hsgc.c']
source=[i for i in os.listdir('.') if i[-2:].lower()=='.c']
testfn=['Rastrigin','Sphere','SchafferF6','Rosenbrock','Griewangk','SchwefelDS','Ackley']
logname=['DERC_01_%s.derc','DERC_02_%s.derc','DERC_03_%s.derc','GABC_%s.gabc','GAGC_%s.gagc','HSBC_%s.hsbc','HSGC_%s.hsgc','HSRC_%s.hsrc']
d={}
d['LOGFILENAME']=''
d['test_function']=''
def change_param(cfile,ofile,d):
    f=open(ofile,'w')
    for i in open(cfile).readlines():
        t=i.strip().split()
        if len(t)>=3 and t[0].strip().lower()=="#define" and t[1].strip() in d.keys():
                t[2]=d[t[1].strip()]
                f.write("%s\n" % " ".join(t))
        else:
            f.write(i)

for cfile in source:
    for fn in testfn:
        lgt,lgx=os.path.splitext(cfile)
        lg="%s.%s" %(fn,lgt)
        tf="g02%s" % fn
        ccfile="%s_%s.c" % (lgt,fn.lower())
        efile="%s_%s.exe" % (lgt,fn.lower())
        d['LOGFILENAME']='"%s"' % lg
        d['test_function']=tf
        printf("Changing '%s' to '%s' ... ",cfile, ccfile)
        change_param(cfile,ccfile,d)
        printf("Done!\n")
        printf("Compiling '%s' to '%s' ... ",ccfile,efile)
        os.system("gcc %s -o %s" %(ccfile,efile))
        printf("Done!\n")
